<?php

namespace app\admin\validate\shop\goods;

use app\shop\library\ShopHelper;
use think\Validate;

class Goods extends Validate
{
    protected $failException = true;

    /**
     * 验证规则
     */
    protected $rule = [
        'status'               => 'checkStatus',
        'name'                 => 'require',
        'classify_id'          => 'require',
        'images'               => 'require',
        'delivery_type'        => 'require',
        'delivery_template_id' => 'checkDeliveryTemplateId'
    ];

    /**
     * 提示消息
     */
    protected $message = [
        'name.require'                                 => '商品名称不能为空',
        'classify_id.require'                          => '商品分类不能为空',
        'images.require'                               => '商品图片不能为空',
        'status.checkStatus'                           => '商品状态不能为空',
        'delivery_type.require'                        => '商品配送方式不能为空',
        'delivery_template_id.checkDeliveryTemplateId' => '商品运费模板不能为空',
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => [],
        'edit' => [],
    ];

    protected function checkStatus($value, $rule, $data = []): bool
    {
        if (count($data) === 2 && isset($data['id']) && isset($data['status'])) {
            $this->only(['status']);
            return !ShopHelper::is_empty($data['status']);
        }
        return true;
    }

    protected function checkDeliveryTemplateId($value, $rule, $data = []): bool
    {
        if ($data['delivery_type'] == 2 && $data['delivery_template_id'] <= 0) {
            return false;
        }

        return true;
    }
}
